//
//  GoodListViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/10/17.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "OYCountDownManager.h"

#import "CardGoodsItemCell.h"

#import "GoodListViewController.h"

#import "GoodDetailViewController.h"

NSString *const k_AuctionListItemSource = @"k_AuctionListItemSource";

@interface GoodListViewController ()
<
UITextFieldDelegate,
UICollectionViewDelegate,
UICollectionViewDataSource
>{
    CGSize _cellSize;
    UIEdgeInsets _collectionEdge;
}

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) UICollectionView *collectionview;

@property (nonatomic, strong) NSMutableArray <HomeProductItemModel *>* dataArray;

@end

@implementation GoodListViewController

- (void)dealloc {
    
    [kCountDownManager removeSourceWithIdentifier:k_AuctionListItemSource];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self refreshParam];
    [self request_GoodsList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [kCountDownManager start];
    [kCountDownManager addSourceWithIdentifier:k_AuctionListItemSource];
}

- (void)reloadTime {
    [kCountDownManager reloadSourceWithIdentifier:k_AuctionListItemSource];
}

- (void)refreshParam {
    
    self.pageNum = 1;
    self.pageSize = 100;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self doSearchAction];
    
    return YES;
}

- (void)request_GoodsList {
    
    [self reloadTime];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    switch (self.type) {
        case PP_GOODLIST_TYPE_SEARCH:{
            [dic setValue:self.itemTitle forKey:@"keyWord"];
        } break;
        case PP_GOODLIST_TYPE_CATEGORY:{
            [dic setValue:self.categoryID forKey:@"id"];
        } break;
        default:
            break;
    }
    
    [dic setValue:@(self.pageNum) forKey:@"curPage"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_SHOP_FINDSHOPLIST];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [self.collectionview.mj_header endRefreshing];
        [self.collectionview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:self.view];
        
        //返回data为字典
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            //请求成功
            if ([code isEqualToString:@"200"]) {
                
                NSArray *resultArray = [data valueForKey:@"data"];
                if ([resultArray isKindOfClass:[NSArray class]]) {
                    

                    if (self.pageNum == 1) {
                        self.dataArray = @[].mutableCopy;
                        
                        if (resultArray.count < self.pageSize) {
                            [self.collectionview.mj_footer endRefreshingWithNoMoreData];
                        }
                    }
                    
                    for (int i = 0; i < resultArray.count; i++) {
                        NSDictionary *productDic = [resultArray objectAtIndex:i];
                        HomeProductItemModel *productModel = [[HomeProductItemModel alloc] init];
                        productModel.productID =    [productDic valueForKey:@"id"];
                        productModel.productName =  [productDic valueForKey:@"goodsName"];
                        productModel.productImage = [productDic valueForKey:@"coverImgPath"];
                        
                        productModel.auctionPrice = [[productDic valueForKey:@"goodsStartingPrice"] doubleValue];
                        productModel.marketPrice =  [[productDic valueForKey:@"goodsMarketPrice"] doubleValue];
                        
                        productModel.goodDetailType =(PPGoodDetailType)[[productDic valueForKey:@"goodDetailType"] integerValue];

                        
                        productModel.beginTimestamp =  [[productDic valueForKey:@"startTime"] doubleValue];
                        productModel.endTimestamp =    [[productDic valueForKey:@"endTime"] doubleValue];//2019-08-02
                        
                        productModel.countDownSource = k_AuctionListItemSource;
                        
                        [self.dataArray addObject:productModel];
                    }
                    
                    if (resultArray.count == 0) {
                        WEAKSELF
                        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:kTTViewStateNoData btnTitle:@"刷新看看" didPressButton:^{
                            [weakSelf request_GoodsList];
                        }];
                        
                    } else {
                        
                    }
                }
                
            } else {
                
                if (self.pageNum == 1) {
                    [self.dataArray removeAllObjects];
                }
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
                
                WEAKSELF
                [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:kTTViewStateNoData btnTitle:@"重新加载" didPressButton:^{
                    [weakSelf request_GoodsList];
                }];
            }
            
            
        } else {
            
            if (self.pageNum == 1) {
                [self.dataArray removeAllObjects];
            }
            
            [SVProgressHUD showErrorWithStatus:@"返回为空"];
            [SVProgressHUD dismissWithDelay:1];
        }
        
        [self.collectionview reloadData];
        

        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_GoodsList];
        }];
        
    }];    
}

- (void)doSearchAction {
    [self.searchTextField resignFirstResponder];
    
    if (self.searchTextField.text.length) {
        self.itemTitle = self.searchTextField.text;
        [self refreshParam];
        [self request_GoodsList];
    } else {
        [self alert:@"请输入关键词"];
    }
}

- (void)initView {
    
    CGFloat width = TTScreenWidth;
    CGFloat cellWidth;
    CGFloat distance = 5;
    cellWidth = width/2 - 2*distance;
    
    _cellSize =  CGSizeMake(cellWidth, cellWidth + 90);//35:52
    _collectionEdge = UIEdgeInsetsMake(distance, distance, distance, distance);
    
    switch (self.type) {
        case PP_GOODLIST_TYPE_SEARCH:{
            
            self.searchTextField.text = self.itemTitle;
            self.navigationItem.titleView = self.searchTextField;
            self.searchTextField.frame = CGRectMake(0, 0, TTScreenWidth - 60, 32);
            
        } break;
        case PP_GOODLIST_TYPE_CATEGORY:{
            
            self.title = self.itemTitle;

        } break;
        default:
            break;
    }
    
    self.view.backgroundColor = UIColorHex(0xf1f1f1);
    
    [self.view addSubview:self.collectionview];
    
    [self.collectionview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.mas_equalTo(0);
    }];
    
}

#pragma mark collectionDelegate & dataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CardGoodsItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CardGoodsItemCellID" forIndexPath:indexPath];
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
 sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return _cellSize;
}

//设置cell的位置
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section {
    return _collectionEdge;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GoodDetailViewController *detailVC = [[GoodDetailViewController alloc] init];
    detailVC.goodsID = self.dataArray[indexPath.row].productID;
    detailVC.type = self.dataArray[indexPath.row].goodDetailType;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (UICollectionView *)collectionview {
    if (!_collectionview) {
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _collectionview  = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
        _collectionview.delegate = self;
        _collectionview.dataSource = self;
        _collectionview.backgroundColor = PP_Default_Color_Gray_F1F1F1;
        [_collectionview registerNib:[UINib nibWithNibName:@"CardGoodsItemCell" bundle:nil] forCellWithReuseIdentifier:@"CardGoodsItemCellID"];
        
        WEAKSELF
        _collectionview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{

            [weakSelf refreshParam];
            [weakSelf request_GoodsList];
        }];
        
        _collectionview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{

            weakSelf.pageNum ++;
            [weakSelf request_GoodsList];
        }];
    }
    return _collectionview;
}

- (UITextField *)searchTextField {
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc]init];
        _searchTextField.backgroundColor = UIColorHex(0xf0f0f0);
        _searchTextField.delegate = self;
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTextField.placeholder = @"输入关键词搜索";
        _searchTextField.font = [UIFont fontWithName:@"Arial" size:14];
        _searchTextField.frame = CGRectMake(0, 6, TTScreenWidth - 60, 32);
        _searchTextField.layer.cornerRadius = 6;
        _searchTextField.layer.masksToBounds = YES;
        
        UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        searchBtn.frame = CGRectMake(0, 0, 30, 30);
        searchBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        [searchBtn addTarget:self action:@selector(doSearchAction) forControlEvents:UIControlEventTouchUpInside];
        [searchBtn setImage:[UIImage imageNamed:@"search_icon"] forState:UIControlStateNormal];
        
        _searchTextField.leftView = searchBtn;
        _searchTextField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _searchTextField;
}

- (NSMutableArray<HomeProductItemModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}
@end
